package com.jack.leetcode.math;

/*** 
 * @author zhangjie
 * @date 2020/5/8 22:12
 */
public class 整数反转 {

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        int x = 1534236469;
        System.out.println(reverse(x));
        x = -120;
        System.out.println(reverse(x));
    }

    public static int reverse(int x) {
        int result = 0;
        if(x == 0){
            return result;
        }
        if (x > 0) {
            StringBuilder s = new StringBuilder(x + "").reverse();
            while (s.charAt(0) == '0') {
                s.deleteCharAt(0);
            }
            try{
                result = Integer.valueOf(s.toString());
            }catch (Exception e){
                return 0;
            }
        } else {
            StringBuilder s = new StringBuilder(Math.abs(x) + "").reverse();
            while (s.charAt(0) == '0') {
                s.deleteCharAt(0);
            }
            try{
                result = -Integer.valueOf(s.toString());
            }catch (Exception e){
                return 0;
            }
        }
        return result;
    }
}
